/**
 * 流式处理工具函数
 */

// 流式数据解析器
async function* XStream({ readableStream }) {
  const reader = readableStream.getReader()
  const decoder = new TextDecoder()
  let buffer = ''

  try {
    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n')
      buffer = lines.pop() || ''

      for (const line of lines) {
        if (line.trim()) {
          yield { data: line.trim() }
        }
      }
    }
  } finally {
    reader.releaseLock()
  }
}

// SSE流式请求业务知识 - 支持POST请求
export const getBusinessKnowledgeStream = (query, config = {}) => {
  return new Promise((resolve, reject) => {
    // 构建POST请求的数据
    const postData = { query }
    
    // 构建完整的URL
    const baseUrl = import.meta.env.VITE_BASE_API2 || 'http://localhost:83'
    const url = `${baseUrl}/api/knowledge`
    
    // 由于EventSource只支持GET请求，我们需要使用fetch来处理POST的SSE
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream',
        'Cache-Control': 'no-cache',
      },
      body: JSON.stringify(postData),
      signal: config.signal, // 支持取消请求
    })
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      if (!response.body) {
        throw new Error('Response body is null')
      }
      
      // 直接返回response.body作为ReadableStream
      resolve(response.body)
    })
    .catch(error => {
      console.error('SSE POST请求失败:', error)
      reject(error)
    })
  })
}

// 处理流式消息的函数
export const processStreamMessage = async (readableStream, messageId, updateCallback) => {
  const lines = []
  let thinkingContent = '' // 思考阶段内容
  let answerContent = '' // 回答阶段内容
  let sources = []
  let isCompleted = false
  let isAnswering = false // 是否进入回答阶段

  // 添加延迟函数，控制思考阶段输出速度
  const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

  try {
    for await (const chunk of XStream({ readableStream })) {
      console.log('收到流式数据:', chunk)
      lines.push(chunk)

      // 解析数据并拼接内容
      try {
        const data = JSON.parse(chunk.data)

        // 处理嵌套的content结构
        if (data.content) {
          const content = data.content

          // 根据不同的stage处理不同的消息
          switch (content.stage) {
            case 'start':
              thinkingContent += `🔍 ${content.message}\n\n`
              break
            case 'rag_start':
              thinkingContent += `📚 ${content.message}\n`
              break
            case 'rag_complete':
              thinkingContent += `✅ ${content.message}\n\n`
              // 提取文档来源信息但不立即显示
              if (content.ans && Array.isArray(content.ans)) {
                sources = content.ans.map((item) => ({
                  content: item.content,
                  metadata: item.metadata,
                }))
                console.log('提取到sources:', sources)
              }
              break
            case 'kg_start':
              thinkingContent += `🧠 ${content.message}\n`
              break
            case 'kg_complete':
              thinkingContent += `✅ ${content.message}\n\n`
              break
            case 'networking_start':
              thinkingContent += `🌐 ${content.message}\n`
              break
            case 'networking_complete':
              thinkingContent += `✅ ${content.message}\n\n`
              break
            case 'csv_start':
              thinkingContent += `📊 ${content.message}\n`
              break
            case 'csv_complete':
              thinkingContent += `✅ ${content.message}\n\n`
              break
            case 'llm_start':
              isAnswering = true // 标记进入回答阶段
              answerContent += `🤖 正在生成回答...\n\n` // 添加换行
              break
            case 'llm_streaming':
              // 这里处理实际的AI回答内容
              if (content.message) {
                answerContent += content.message
              }
              break
            case 'complete':
            case 'llm_complete':
              // 添加完成标记和换行
              if (answerContent && !answerContent.endsWith('\n')) {
                answerContent += '\n'
              }
              answerContent += `\n\n✅ 回答完成`
              isCompleted = true
              // 流式完成后，带上sources一起更新
              updateCallback(messageId, {
                text: answerContent,
                thinking: thinkingContent,
                isTyping: false,
                isStreaming: false,
                loading: false,
                sources: sources,
                streamCompleted: true,
              })
              return // 直接返回，不再继续处理
            default:
              // 处理其他类型的消息
              if (content.message) {
                if (isAnswering) {
                  answerContent += content.message
                } else {
                  thinkingContent += content.message
                }
              }
          }

          // 在思考阶段添加延迟，控制输出速度
          if (!isAnswering && !isCompleted) {
            await delay(300) // 思考阶段每次更新延迟300ms
          }

          // 实时更新消息内容，但不传递sources
          if (!isCompleted) {
            updateCallback(messageId, {
              text: answerContent || 'AI正在思考中...',
              thinking: thinkingContent,
              isTyping: isAnswering,
              isStreaming: true,
              loading: false,
              sources: [], // 流式过程中不显示sources
            })
          }
        }
      } catch (parseError) {
        console.warn('解析流式数据失败:', parseError, chunk)
      }
    }

    // 流结束，如果没有收到complete信号，也要显示sources
    if (!isCompleted) {
      updateCallback(messageId, {
        text: answerContent,
        thinking: thinkingContent,
        isTyping: false,
        isStreaming: false,
        loading: false,
        sources: sources,
        streamCompleted: true,
      })
    }

    return { content: answerContent, sources }
  } catch (error) {
    console.error('处理流式消息失败:', error)
    updateCallback(messageId, {
      text: '获取回复失败',
      thinking: '',
      isTyping: false,
      isStreaming: false,
      loading: false,
      error: true,
    })
    throw error
  }
}

// 简化的流式处理函数（用于赛力斯问答）
export const processSailisiStream = async (readableStream, messageId, updateCallback) => {
  const reader = readableStream.getReader()
  const decoder = new TextDecoder()
  let buffer = ''
  let finalAnswer = ''
  let thinkingContent = '' // 累积思考过程
  let isStreaming = true

  // 添加延迟函数，控制流式输出速度
  const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

  try {
    console.log('开始处理赛力斯流式数据...')
    
    // 先显示流式状态
    updateCallback(messageId, {
      text: 'AI正在思考中...',
      isTyping: true,
      isStreaming: true,
      loading: false
    })

    let chunkCount = 0
    while (true) {
      const { done, value } = await reader.read()
      if (done) {
        console.log('流式数据读取完成')
        break
      }

      chunkCount++
      console.log(`收到第${chunkCount}个数据块:`, value.length, '字节')

      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n')
      buffer = lines.pop() || ''

      console.log('当前buffer内容:', buffer)
      console.log('解析出的行数:', lines.length)

      for (const line of lines) {
        console.log('处理行:', line)
        if (line.startsWith('data:')) {
          try {
            const jsonStr = line.slice(5).trim()
            console.log('解析JSON:', jsonStr)
            const data = JSON.parse(jsonStr)
            console.log('解析后的数据:', data)
            
            if (data.content) {
              const content = data.content
              console.log('处理内容阶段:', content.stage, content.message)
              
              // 处理不同的阶段
              if (content.stage === 'llm_processing' || content.stage === 'llm_streaming') {
                if (content.message) {
                  finalAnswer += content.message
                  console.log('累积回答:', finalAnswer)
                  // 实时更新消息，添加延迟控制
                  updateCallback(messageId, {
                    text: finalAnswer,
                    isTyping: true,
                    isStreaming: true,
                    loading: false
                  })
                  await delay(100) // 控制输出速度
                }
              } else if (content.stage === 'complete' || content.stage === 'llm_complete') {
                console.log('流式处理完成')
                isStreaming = false
                updateCallback(messageId, {
                  text: finalAnswer,
                  thinking: thinkingContent,
                  isTyping: false,
                  isStreaming: false,
                  loading: false
                })
                return { answer: finalAnswer }
              } else {
                // 处理其他阶段的消息，显示思考过程
                console.log('处理思考阶段消息:', content.stage, content.message)
                let thinkingMessage = ''
                
                switch (content.stage) {
                  case 'start':
                    thinkingMessage = `🔍 ${content.message}\n\n`
                    break
                  case 'rag_start':
                    thinkingMessage = `📚 ${content.message}\n`
                    break
                  case 'rag_complete':
                    thinkingMessage = `✅ ${content.message}\n\n`
                    break
                  case 'kg_start':
                    thinkingMessage = `🧠 ${content.message}\n`
                    break
                  case 'kg_complete':
                    thinkingMessage = `✅ ${content.message}\n\n`
                    break
                  case 'networking_start':
                    thinkingMessage = `🌐 ${content.message}\n`
                    break
                  case 'networking_complete':
                    thinkingMessage = `✅ ${content.message}\n\n`
                    break
                  case 'csv_start':
                    thinkingMessage = `📊 ${content.message}\n`
                    break
                  case 'csv_complete':
                    thinkingMessage = `✅ ${content.message}\n\n`
                    break
                  case 'llm_start':
                    thinkingMessage = `🤖 ${content.message}\n\n`
                    break
                  default:
                    thinkingMessage = content.message ? `${content.message}\n` : ''
                }
                
                if (thinkingMessage) {
                  // 累积思考过程
                  thinkingContent += thinkingMessage
                  console.log('累积思考内容:', thinkingContent)
                  
                  // 更新思考过程
                  updateCallback(messageId, {
                    text: finalAnswer || 'AI正在思考中...',
                    thinking: thinkingContent,
                    isTyping: true,
                    isStreaming: true,
                    loading: false
                  })
                  await delay(200) // 控制思考过程显示速度
                }
              }
            }
          } catch (e) {
            console.log('解析SSE数据失败:', e, line)
          }
        }
      }
    }
    
    // 流结束
    console.log('流式处理结束，最终回答:', finalAnswer)
    isStreaming = false
    updateCallback(messageId, {
      text: finalAnswer || '服务响应完成，但未收到内容',
      thinking: thinkingContent,
      isTyping: false,
      isStreaming: false,
      loading: false
    })
    return { answer: finalAnswer || '服务响应完成，但未收到内容' }
  } catch (error) {
    console.error('处理赛力斯流式消息失败:', error)
    updateCallback(messageId, {
      text: '获取回复失败',
      isTyping: false,
      isStreaming: false,
      loading: false,
      error: true
    })
    throw error
  } finally {
    reader.releaseLock()
  }
}
